#!/usr/bin/env python3
"""
视频转码系统主程序入口（完整界面版本）

基于Python + PyQt6开发的高性能视频转码系统，
支持多GPU并行转码和实时监控的单体桌面应用。
"""

import sys
import os
from pathlib import Path

# 添加src目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

from PyQt6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, 
                             QWidget, QLabel, QTreeWidget, QTreeWidgetItem, QTabWidget,
                             QProgressBar, QPushButton, QMenuBar, QMenu,
                             QDialog, QDialogButtonBox, QSplitter, QStatusBar, QScrollArea)
from PyQt6.QtCore import QTimer, Qt
from PyQt6.QtGui import QIcon, QFont, QAction

# 导入转码任务UI组件
from transcode_task_ui import TranscodeTaskDialog
# 导入紧凑仪表盘组件
from ui.gauge_widget import CompactHardwareMonitor


class MenuSystem:
    """菜单系统类"""
    
    def __init__(self, main_window):
        self.main_window = main_window
        self.menu_bar = None
        
    def init_menu_system(self):
        """初始化完整的菜单系统"""
        self.menu_bar = self.main_window.menuBar()
        
        # 文件菜单
        file_menu = self.menu_bar.addMenu("文件(&F)")
        self._add_menu_item(file_menu, "新建任务", "Ctrl+N", self.new_task)
        self._add_menu_item(file_menu, "打开任务", "Ctrl+O", self.open_task)
        file_menu.addSeparator()
        self._add_menu_item(file_menu, "退出", "Ctrl+Q", self.main_window.close)
        
        # 编辑菜单
        edit_menu = self.menu_bar.addMenu("编辑(&E)")
        self._add_menu_item(edit_menu, "撤销", "Ctrl+Z", self.undo_action)
        self._add_menu_item(edit_menu, "重做", "Ctrl+Y", self.redo_action)
        edit_menu.addSeparator()
        self._add_menu_item(edit_menu, "复制", "Ctrl+C", self.copy_action)
        self._add_menu_item(edit_menu, "粘贴", "Ctrl+V", self.paste_action)
        
        # 视图菜单
        view_menu = self.menu_bar.addMenu("视图(&V)")
        self._add_menu_item(view_menu, "资源监控", "Ctrl+R", self.show_resource_monitor)
        self._add_menu_item(view_menu, "转码任务", "Ctrl+T", self.show_transcode_tasks)
        self._add_menu_item(view_menu, "系统设置", "Ctrl+S", self.show_system_settings)
        
        # 设置菜单
        settings_menu = self.menu_bar.addMenu("设置(&S)")
        self._add_menu_item(settings_menu, "常规设置", None, self.show_general_settings)
        self._add_menu_item(settings_menu, "编码设置", None, self.show_encoder_settings)
        self._add_menu_item(settings_menu, "硬件设置", None, self.show_hardware_settings)
        
        # 帮助菜单
        help_menu = self.menu_bar.addMenu("帮助(&H)")
        self._add_menu_item(help_menu, "关于", None, self.show_about_dialog)
        self._add_menu_item(help_menu, "文档", "F1", self.show_documentation)
        self._add_menu_item(help_menu, "检查更新", None, self.check_for_updates)
    
    def _add_menu_item(self, menu, text, shortcut, callback):
        """添加菜单项"""
        action = QAction(text, self.main_window)
        if shortcut:
            action.setShortcut(shortcut)
        action.triggered.connect(callback)
        menu.addAction(action)
    
    def new_task(self):
        """新建任务"""
        # 创建转码任务对话框
        task_dialog = TranscodeTaskDialog(self.main_window)
        task_dialog.exec()
    
    def open_task(self):
        """打开任务"""
        self.show_placeholder_dialog("打开任务", "打开转码任务功能开发中...")
    
    def undo_action(self):
        """撤销操作"""
        self.show_placeholder_dialog("撤销", "撤销功能开发中...")
    
    def redo_action(self):
        """重做操作"""
        self.show_placeholder_dialog("重做", "重做功能开发中...")
    
    def copy_action(self):
        """复制操作"""
        self.show_placeholder_dialog("复制", "复制功能开发中...")
    
    def paste_action(self):
        """粘贴操作"""
        self.show_placeholder_dialog("粘贴", "粘贴功能开发中...")
    
    def show_resource_monitor(self):
        """显示资源监控"""
        self.show_placeholder_dialog("资源监控", "资源监控界面开发中...")
    
    def show_transcode_tasks(self):
        """显示转码任务"""
        self.show_placeholder_dialog("转码任务", "转码任务界面开发中...")
    
    def show_system_settings(self):
        """显示系统设置"""
        self.show_placeholder_dialog("系统设置", "系统设置界面开发中...")
    
    def show_general_settings(self):
        """显示常规设置"""
        self.show_placeholder_dialog("常规设置", "常规设置界面开发中...")
    
    def show_encoder_settings(self):
        """显示编码设置"""
        self.show_placeholder_dialog("编码设置", "编码设置界面开发中...")
    
    def show_hardware_settings(self):
        """显示硬件设置"""
        self.show_placeholder_dialog("硬件设置", "硬件设置界面开发中...")
    
    def show_about_dialog(self):
        """显示关于对话框"""
        dialog = QDialog(self.main_window)
        dialog.setWindowTitle("关于 - 视频转码系统")
        dialog.setMinimumSize(800, 600)
        
        # 创建主布局
        main_layout = QVBoxLayout()
        
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        
        # 创建内容部件
        content_widget = QWidget()
        content_layout = QVBoxLayout(content_widget)
        
        # 读取并显示Markdown内容
        about_content = self._load_about_content()
        content_label = QLabel(about_content)
        content_label.setWordWrap(True)
        content_label.setTextFormat(Qt.TextFormat.RichText)
        content_layout.addWidget(content_label)
        
        # 设置滚动区域内容
        scroll_area.setWidget(content_widget)
        main_layout.addWidget(scroll_area)
        
        # 添加确定按钮
        button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
        button_box.accepted.connect(dialog.accept)
        main_layout.addWidget(button_box)
        
        dialog.setLayout(main_layout)
        dialog.exec()
    
    def _load_about_content(self):
        """加载关于内容Markdown文件并转换为HTML格式"""
        try:
            # 读取Markdown文件
            about_file = Path(__file__).parent / "about_content.md"
            with open(about_file, 'r', encoding='utf-8') as f:
                markdown_content = f.read()
            
            # 简单的Markdown到HTML转换
            html_content = self._markdown_to_html(markdown_content)
            return html_content
            
        except Exception as e:
            # 如果文件读取失败，返回默认内容
            return f"<h1>视频转码系统 v0.1.0</h1><p>基于Python + PyQt6开发</p><p>无法加载关于内容：{str(e)}</p>"
    
    def _markdown_to_html(self, markdown_text):
        """简单的Markdown到HTML转换"""
        # 替换标题
        html = markdown_text
        
        # 替换一级标题
        html = html.replace('# ', '<h1>')
        html = html.replace('\n# ', '</h1>\n<h1>')
        
        # 替换二级标题
        html = html.replace('## ', '<h2>')
        html = html.replace('\n## ', '</h2>\n<h2>')
        
        # 替换三级标题
        html = html.replace('### ', '<h3>')
        html = html.replace('\n### ', '</h3>\n<h3>')
        
        # 替换粗体
        html = html.replace('**', '<b>')
        html = html.replace('**', '</b>')
        
        # 替换列表项
        html = html.replace('- ', '<li>')
        html = html.replace('\n- ', '</li>\n<li>')
        
        # 替换换行符
        html = html.replace('\n', '<br>')
        
        # 添加基本HTML结构
        html = f"<html><body>{html}</body></html>"
        
        return html
    
    def show_documentation(self):
        """显示文档"""
        self.show_placeholder_dialog("文档", "系统文档开发中...")
    
    def check_for_updates(self):
        """检查更新"""
        self.show_placeholder_dialog("检查更新", "检查更新功能开发中...")
    
    def show_placeholder_dialog(self, title, message):
        """显示占位符对话框"""
        dialog = QDialog(self.main_window)
        dialog.setWindowTitle(title)
        layout = QVBoxLayout()
        layout.addWidget(QLabel(message))
        
        button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
        button_box.accepted.connect(dialog.accept)
        layout.addWidget(button_box)
        
        dialog.setLayout(layout)
        dialog.exec()


class ResourceMonitorUI(QWidget):
    """资源监控界面"""
    
    def __init__(self):
        super().__init__()
        self.tree_widget = None
        self.dashboard_widget = None
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        # 创建主布局
        main_layout = QHBoxLayout()
        
        # 左侧树状导航
        left_panel = QVBoxLayout()
        tree_label = QLabel("📊 硬件监控分类")
        tree_label.setFont(QFont("Microsoft YaHei", 10, QFont.Weight.Bold))
        left_panel.addWidget(tree_label)
        
        self.tree_widget = QTreeWidget()
        self.tree_widget.setHeaderLabels(["硬件组件", "状态", "数值"])
        self.tree_widget.setColumnWidth(0, 200)
        self.tree_widget.setColumnWidth(1, 80)
        self.tree_widget.setColumnWidth(2, 100)
        
        # 添加示例数据
        self._populate_tree()
        left_panel.addWidget(self.tree_widget)
        
        # 右侧仪表盘
        right_panel = QVBoxLayout()
        dashboard_label = QLabel("📈 实时仪表盘")
        dashboard_label.setFont(QFont("Microsoft YaHei", 10, QFont.Weight.Bold))
        right_panel.addWidget(dashboard_label)
        
        self.dashboard_widget = QTabWidget()
        self.dashboard_widget.addTab(self.create_cpu_tab(), "CPU")
        self.dashboard_widget.addTab(self.create_gpu_tab(), "GPU")
        self.dashboard_widget.addTab(self.create_memory_tab(), "内存")
        self.dashboard_widget.addTab(self.create_storage_tab(), "存储")
        right_panel.addWidget(self.dashboard_widget)
        
        main_layout.addLayout(left_panel, 1)
        main_layout.addLayout(right_panel, 2)
        self.setLayout(main_layout)
    
    def _populate_tree(self):
        """填充树状导航数据"""
        # CPU节点
        cpu_root = QTreeWidgetItem(self.tree_widget, ["💻 CPU处理器", "运行中", ""])
        QTreeWidgetItem(cpu_root, ["CPU使用率", "正常", "15%"])
        QTreeWidgetItem(cpu_root, ["CPU温度", "正常", "45°C"])
        QTreeWidgetItem(cpu_root, ["CPU频率", "正常", "3.8GHz"])
        
        # GPU节点
        gpu_root = QTreeWidgetItem(self.tree_widget, ["🎮 GPU显卡", "运行中", ""])
        QTreeWidgetItem(gpu_root, ["GPU使用率", "正常", "8%"])
        QTreeWidgetItem(gpu_root, ["GPU温度", "正常", "52°C"])
        QTreeWidgetItem(gpu_root, ["显存使用", "正常", "1.2/8GB"])
        
        # 内存节点
        memory_root = QTreeWidgetItem(self.tree_widget, ["💾 内存", "运行中", ""])
        QTreeWidgetItem(memory_root, ["内存使用率", "正常", "45%"])
        QTreeWidgetItem(memory_root, ["可用内存", "充足", "8.2GB"])
        
        # 存储节点
        storage_root = QTreeWidgetItem(self.tree_widget, ["💿 存储", "运行中", ""])
        QTreeWidgetItem(storage_root, ["C盘使用率", "正常", "65%"])
        QTreeWidgetItem(storage_root, ["D盘使用率", "正常", "32%"])
        
        # 展开所有节点
        self.tree_widget.expandAll()
    
    def create_cpu_tab(self):
        """创建CPU监控标签页"""
        widget = QWidget()
        layout = QVBoxLayout()
        
        # CPU使用率
        cpu_label = QLabel("CPU使用率: 15%")
        cpu_progress = QProgressBar()
        cpu_progress.setValue(15)
        
        # CPU温度
        temp_label = QLabel("CPU温度: 45°C")
        temp_progress = QProgressBar()
        temp_progress.setValue(45)
        temp_progress.setMaximum(100)
        
        layout.addWidget(cpu_label)
        layout.addWidget(cpu_progress)
        layout.addWidget(temp_label)
        layout.addWidget(temp_progress)
        layout.addStretch()
        
        widget.setLayout(layout)
        return widget
    
    def create_gpu_tab(self):
        """创建GPU监控标签页"""
        widget = QWidget()
        layout = QVBoxLayout()
        
        gpu_label = QLabel("GPU监控数据加载中...")
        layout.addWidget(gpu_label)
        layout.addStretch()
        
        widget.setLayout(layout)
        return widget
    
    def create_memory_tab(self):
        """创建内存监控标签页"""
        widget = QWidget()
        layout = QVBoxLayout()
        
        memory_label = QLabel("内存使用率: 45%")
        memory_progress = QProgressBar()
        memory_progress.setValue(45)
        
        layout.addWidget(memory_label)
        layout.addWidget(memory_progress)
        layout.addStretch()
        
        widget.setLayout(layout)
        return widget
    
    def create_storage_tab(self):
        """创建存储监控标签页"""
        widget = QWidget()
        layout = QVBoxLayout()
        
        storage_label = QLabel("存储监控数据加载中...")
        layout.addWidget(storage_label)
        layout.addStretch()
        
        widget.setLayout(layout)
        return widget


class VideoTranscoderApp(QMainWindow):
    """视频转码系统主窗口"""
    
    def __init__(self):
        super().__init__()
        self.menu_system = None
        self.status_bar = None
        self.hardware_monitor = None
        self.update_timer = QTimer()
        self.init_ui()
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("视频转码系统")
        self.setGeometry(100, 100, 1400, 900)
        
        # 初始化菜单系统
        self.menu_system = MenuSystem(self)
        self.menu_system.init_menu_system()
        
        # 初始化状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("系统就绪 - 欢迎使用视频转码系统")
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        

        
        # 添加紧凑硬件监控面板
        self.hardware_monitor = CompactHardwareMonitor()
        main_layout.addWidget(self.hardware_monitor)
        
        # 初始化定时器更新硬件数据
        self.update_timer.timeout.connect(self.update_hardware_data)
        self.update_timer.start(1000)  # 1秒更新一次
        
        # 添加快速操作按钮
        quick_actions = self.create_quick_actions()
        main_layout.addWidget(quick_actions)
    
    def create_quick_actions(self):
        """创建快速操作按钮区域"""
        widget = QWidget()
        layout = QHBoxLayout()
        
        # 新建任务按钮
        new_task_btn = QPushButton("📁 新建转码任务")
        new_task_btn.setStyleSheet("""
            QPushButton {
                font-size: 14px;
                padding: 10px 20px;
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
        """)
        new_task_btn.clicked.connect(self.menu_system.new_task)
        
        # 资源监控按钮
        monitor_btn = QPushButton("📊 资源监控")
        monitor_btn.setStyleSheet("""
            QPushButton {
                font-size: 14px;
                padding: 10px 20px;
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #1e7e34;
            }
        """)
        monitor_btn.clicked.connect(self.menu_system.show_resource_monitor)
        
        # 系统设置按钮
        settings_btn = QPushButton("⚙️ 系统设置")
        settings_btn.setStyleSheet("""
            QPushButton {
                font-size: 14px;
                padding: 10px 20px;
                background-color: #6c757d;
                color: white;
                border: none;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #545b62;
            }
        """)
        settings_btn.clicked.connect(self.menu_system.show_system_settings)
        
        layout.addWidget(new_task_btn)
        layout.addWidget(monitor_btn)
        layout.addWidget(settings_btn)
        layout.addStretch()
        
        widget.setLayout(layout)
        return widget
    
    def update_hardware_data(self):
        """更新硬件监控数据"""
        try:
            import psutil
            
            # 获取CPU使用率
            cpu_usage = psutil.cpu_percent(interval=0.1)
            
            # 获取内存使用率
            memory = psutil.virtual_memory()
            memory_usage = memory.percent
            
            # 尝试获取GPU使用率（需要GPUtil库）
            gpu_usage = 0
            gpu_temp = None
            try:
                import GPUtil
                gpus = GPUtil.getGPUs()
                if gpus:
                    gpu_usage = gpus[0].load * 100
                    gpu_temp = gpus[0].temperature
            except ImportError:
                gpu_usage = 0  # 如果没有GPU库，设为0
            
            # 获取CPU温度（需要额外库支持）
            cpu_temp = None
            try:
                # 尝试使用psutil获取温度（某些系统支持）
                if hasattr(psutil, "sensors_temperatures"):
                    temps = psutil.sensors_temperatures()
                    if 'coretemp' in temps:
                        cpu_temp = temps['coretemp'][0].current
            except:
                pass
            
            # 更新仪表盘
            self.hardware_monitor.update_data(cpu_usage, gpu_usage, memory_usage, cpu_temp, gpu_temp)
            
        except Exception as e:
            print(f"硬件数据更新失败: {e}")


def main():
    """主程序入口"""
    # 创建Qt应用
    app = QApplication(sys.argv)
    app.setApplicationName("视频转码系统")
    app.setApplicationVersion("0.1.0")
    app.setOrganizationName("VideoTranscoder")
    
    # 创建主窗口
    main_window = VideoTranscoderApp()
    main_window.show()
    
    print("🚀 视频转码系统启动成功！")
    print("✅ 完整菜单系统已加载")
    print("✅ 资源监控界面已显示")
    print("✅ 系统状态栏已初始化")
    print("✅ 准备进行功能开发")
    
    # 启动事件循环
    sys.exit(app.exec())


if __name__ == "__main__":
    main()